package org.hbs.blog.code.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BasePathFilter implements Filter {

	private String key = "root";

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String path = req.getContextPath();
		String root = req.getScheme() + "://" + req.getServerName() + ":"
				+ req.getServerPort() + path + "/";
		req.setAttribute(key, root);
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig config) throws ServletException {
		String $key = config.getInitParameter("key");
		this.key = null == $key ? this.key : 
					$key.trim().equals("") ? this.key : $key;
	}

}
